import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_math_fork/flutter_math.dart';
import 'package:math_keyboard/math_keyboard.dart';
import 'package:shared_preferences/shared_preferences.dart';

String _tex = r'';
TextEditingController _textEditingController = TextEditingController(text: _tex);

class RunningPage extends StatefulWidget {

  Future<void> setT(String value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('lastLaTex', value);
  }

  Future<String> getT() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? t = prefs.getString('lastLaTex');
    return t.toString();
  }

  @override
  _RunningPageState createState() => _RunningPageState();
}



class _RunningPageState extends State<RunningPage> {

  late final _controller = MathFieldEditingController();


  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ListView(children: [
        Divider(),
        Padding(
          padding: const EdgeInsets.all(16),
          child: MathField(
            autofocus: false,
            controller: _controller,
            onChanged: (input) {setState(() {
              print(input);
              _tex=input;
            });},
            decoration: InputDecoration(
              hintText: "通过数学键盘生成Tex",
              suffix: MouseRegion(
                cursor: MaterialStateMouseCursor.clickable,
                child: GestureDetector(
                  onTap: _controller.clear,
                  child: const Icon(
                    Icons.highlight_remove_rounded,
                    color: Colors.grey,
                  ),
                ),
              ),
            ),
          ),
        ),
        Container(
          height: 200,
          child: FittedBox(
            fit: BoxFit.contain,
            child: Container(
                padding: EdgeInsets.all(16.0),
                child: Math.tex(
                  _tex,
                  textStyle: TextStyle(fontSize: 12,),mathStyle: MathStyle.display,
                ),            ),
          ),
        ),

        TextField(
          onChanged: (text) {
            setState(() {
              _tex = text.replaceAll("\$", "");
            });
          },
          decoration: InputDecoration(
              hintText: "或者输入tex表达式",
              border: OutlineInputBorder()
          ),
          controller: _textEditingController,
        ),

      ]),
    );
  }
}